package org.example.word.service.impl;

import org.example.order.entity.OrderDO;
import org.example.order.mapper.OrderMapper;
import org.example.word.service.IPdfService;
import org.example.word.utils.DateUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.example.word.process.WordTemplateProcessor;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

@Service
public class PdfServiceImpl implements IPdfService {

    @Resource
    private OrderMapper orderMapper;

    @Value("${word.template.path}")
    private String filePath;

    @Override
    public void generatePdf(Long orderId, HttpServletResponse response) throws Exception {
        Map<String, String> data = getData(orderId);
       // 处理模板并生成PDF
        ByteArrayOutputStream wordOutputStream = WordTemplateProcessor.processTemplate(filePath, data);

        String fileName = "output_" + orderId.toString() + ".docx";
        // 设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
        response.setHeader("Content-Disposition", "attachment; filename=" + fileName);

        // 将PDF内容写入响应体
        try (InputStream pdfInputStream = new ByteArrayInputStream(wordOutputStream.toByteArray());
             OutputStream out = response.getOutputStream()) {
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = pdfInputStream.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
            }
            out.flush();
        }
    }

    private Map<String, String> getData(Long orderId) {
        OrderDO order = orderMapper.selectById(orderId);
        Map<String, String> data = new HashMap<>();
        data.put("name", order.getUserName());
        data.put("sex", order.getUserSex());
        data.put("sx", DateUtils.calculateShengxiao(order.getBirthDate()));
        data.put("birth", order.getBirthDate().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        return data;
    }
}
